const db = require('../db/index');
const mysql = require('mysql');
const fs = require('fs');
const path = require('path');

const myDate = require('../encapsulation/tool/myDate');
const arrMethod = require('../encapsulation/tool/arrMethod');

// 全局配置
const config = require('../config');
// 引入multiparty文件解析方法
const multiparty = require('multiparty');
const multipartyTool = require('../encapsulation/tool/multipartyTool');
const uploadDir = path.resolve(__dirname, '../', 'static/files');

// const axios = require('axios')

// 添加项目
exports.addProject = (req, res) => {
	// 查询项目名称是否被占用
	const sql = 'select * from project where project_name=? and project_delete=0';
	db.query(sql, req.body.project_name, (err, results) => {
		if (err) return res.cc(err);
		if (results.length === 1) return res.cc('项目名称重复请重新输入');
		// 计算项目时间，并给req.body附加 项目时间 属性
		let project_days = myDate.exdateDiff(req.body.project_start_date, req.body.project_end_date);
		req.body.project_days = project_days;
		// 将 req.body.project_groups 的字符串 转为 数组 userArr
		let userArr = req.body.project_groups.split('@');
		// 计算项目人数，并给req.body附加 项目人数 属性
		let index = 0
		userArr.map(item => {
			if(item == req.body.project_service){ index++ }
			if(item == req.body.project_leader){ index++ }
		})
		req.body.project_people_number = userArr.length + 2 - index;
		// 添加项目表
		const sql = 'insert into project set ?';
		db.query(sql, req.body, (err, results) => {
			if (err) return res.cc(err);
			res.cc('添加成功', 0);
		})
	})
}

// 编辑项目
exports.updateProject = (req, res) => {
	// 查询项目名称是否被占用
	const sql = 'select * from project where project_id<>? and project_name=? and project_delete=0';
	db.query(sql, [req.body.project_id, req.body.project_name], (err, results) => {
		if (err) return res.cc(err);
		if (results.length === 1) return res.cc('项目名称重复请重新输入');
		// 计算项目时间，并给req.body附加 项目时间 属性
		let project_days = myDate.exdateDiff(req.body.project_start_date, req.body.project_end_date);
		req.body.project_days = project_days;
		// 将 req.body.project_groups 的字符串 转为 数组 userArr
		let userArr = req.body.project_groups.split('@');
		// 计算项目人数，并给req.body附加 项目人数 属性
		let project_people_number = 2 + userArr.length;
		req.body.project_people_number = project_people_number;
		// 添加项目表 update user set ? where id=?
		const sql = 'update project set ? where project_id=?';
		db.query(sql, [req.body, req.body.project_id], (err, results) => {
			if (err) return res.cc(err);
			res.cc('更新成功', 0);
		})
	})
}

// 删除项目
exports.deleteProject = (req, res) => {
	const sql = 'update project set project_delete=1 where project_id=?';
	db.query(sql, req.body.project_id, (err, results) => {
		if (err) return res.cc(err);
		res.cc('删除成功', 0);
	})
}

// 日历项目查询
exports.getProject = (req, res) => {
	// 对传递过来的日期进行格式化
	// req.query.start_date = myDate.jsDateFormatter(req.query.start_date);
	// req.query.end_date = myDate.jsDateFormatter(req.query.end_date);
	// 根据时间段进行查询
	const sql = `
		select * from project 
		where
		((project_start_date >= '` + req.query.start_date + `' and project_start_date<= '` + req.query.end_date + `')
		or (project_end_Date >= '` + req.query.start_date + `' and project_end_Date<= '` + req.query.end_date + `')
		or (project_start_date <= '` + req.query.start_date + `' and project_end_Date>= '` + req.query.end_date + `'))
		and project_delete=0
		`;
	db.query(sql, (err, results) => {
		if (err) return res.cc(err);
		let arr = results.map((item) => {
			return Object.assign({}, {
					project_id: item.project_id
				}, // id
				{
					project_name: item.project_name
				}, // 项目名
				{
					project_start_date: item.project_start_date
				}, // 项目开启日期
				{
					project_first_date: item.project_first_date
				}, // 项目初稿日期
				{
					project_end_date: item.project_end_date
				}, // 项目结束日期
				{
					project_type: item.project_type
				}, // 项目类型
				{
					project_leader_id: item.project_leader
				}, // 项目组长id
				{
					project_groups: item.project_groups
				}, // 项目组员们id
				{
					project_state: item.project_state
				} // 项目当前状态
			)
		})
		// 查询用户列表，添加用户字段
		const sql = 'select * from user';
		db.query(sql, (err, results) => {
			if (err) return res.cc(err);
			for (let i = 0; i < arr.length; i++) {
				// 将字符串转为数组
				arr[i].project_groups = arr[i].project_groups.split('@')
				for (let j = 0; j < results.length; j++) {
					// 给组长添加昵称属性
					if (arr[i].project_leader_id === results[j].id) {
						arr[i].project_leader_name = results[j].nick_name
					}
					// 给组员添加昵称属性
					for (let k = 0; k < arr[i].project_groups.length; k++) {
						if (arr[i].project_groups[k] == results[j].id) {
							arr[i].project_groups[k] = {
								project_groups: arr[i].project_groups[k],
								project_groups_name: results[j].nick_name
							}
						}
					}
				}
			}
			res.send({
				status: 0,
				message: '查询成功',
				data: arr
			});
		})
	});
}

// 根据项目名查询项目
exports.getProjectName = (req, res) => {
	// 项目名进行处理
	const name = '%' + req.body.project_name + '%';
	// 对传递过来的日期进行格式化
	req.body.start_date = myDate.jsDateFormatter(req.body.start_date);
	req.body.end_date = myDate.jsDateFormatter(req.body.end_date);
	const sql = `
		select * from project 
		where
		((project_start_date >= '` + req.body.start_date + `' and project_start_date<= '` + req.body.end_date + `')
		or (project_end_Date >= '` + req.body.start_date + `' and project_end_Date<= '` + req.body.end_date + `')
		or (project_start_date <= '` + req.body.start_date + `' and project_end_Date>= '` + req.body.end_date + `'))
		and project_delete=0 and project_name like ?
		`;
	db.query(sql, name, (err, results) => {
		let arr = results.map((item) => {
			return Object.assign({}, {
					project_id: item.project_id
				}, // id
				{
					project_name: item.project_name
				}, // 项目名
				{
					project_start_date: item.project_start_date
				}, // 项目开启日期
				{
					project_first_date: item.project_first_date
				}, // 项目初稿日期
				{
					project_end_date: item.project_end_date
				}, // 项目结束日期
				{
					project_type: item.project_type
				}, // 项目类型
				{
					project_leader_id: item.project_leader
				}, // 项目组长id
				{
					project_groups: item.project_groups
				}, // 项目组员们id
				{
					project_state: item.project_state
				} // 项目当前状态
			)
		})
		// 查询用户列表，添加用户字段
		const sql = 'select * from user';
		db.query(sql, (err, results) => {
			if (err) return res.cc(err);
			for (let i = 0; i < arr.length; i++) {
				// 将字符串转为数组
				arr[i].project_groups = arr[i].project_groups.split('@')
				for (let j = 0; j < results.length; j++) {
					// 给组长添加昵称属性
					if (arr[i].project_leader_id === results[j].id) {
						arr[i].project_leader_name = results[j].nick_name
					}
					// 给组员添加昵称属性
					for (let k = 0; k < arr[i].project_groups.length; k++) {
						if (arr[i].project_groups[k] == results[j].id) {
							arr[i].project_groups[k] = {
								project_groups: arr[i].project_groups[k],
								project_groups_name: results[j].nick_name
							}
						}
					}
				}
			}
			res.send({
				status: 0,
				message: '查询成功',
				data: arr
			});
		})
	})
}

// 查询项目详情
exports.getProjectBody = (req, res) => {
	const sql = 'select * from project where project_id=?';
	db.query(sql, req.query.project_id, (err, results) => {
		let arr = results;
		// 查询用户列表，添加用户字段
		const sql = 'select * from user';
		db.query(sql, (err, results) => {
			if (err) return res.cc(err);
			for (let i = 0; i < arr.length; i++) {
				// 将字符串转为数组
				arr[i].project_groups = arr[i].project_groups.split('@')
				for (let j = 0; j < results.length; j++) {
					// 给组长和客服添加昵称属性
					if (arr[i].project_leader === results[j].id) {
						arr[i].project_leader_name = results[j].nick_name
					}
					if (arr[i].project_service === results[j].id) {
						arr[i].project_service_name = results[j].nick_name
					}
					// 给组员添加昵称属性
					for (let k = 0; k < arr[i].project_groups.length; k++) {
						if (arr[i].project_groups[k] == results[j].id) {
							arr[i].project_groups[k] = {
								project_groups: arr[i].project_groups[k],
								project_groups_name: results[j].nick_name
							}
						}
					}
				}
			}
			// 查询项目列表，并用projectArr接收
			const sql = 'select * from project where project_delete=0 order by project_id desc';
			db.query(sql, (err, results) => {
				if (err) return res.cc(err);
				let projectArr = results.map(item => {
					return Object.assign(
						{},
						{project_id: item.project_id},
						{project_name: item.project_name}
					)
				})
				// 查询项目相册，并用projectImageArr接收
				const sql = 'select * from project_images where project_id=? order by project_images_id desc';
				db.query(sql, req.query.project_id, (err, results) => {
					if (err) return res.cc(err);
					let projectImageArr = results;
					res.send({
						status: 0,
						message: '查询成功',
						data: [arr, projectArr, projectImageArr]
					});
				})
			})
		})
	})
}

// 分页查询项目列表
exports.getProjectList = (req, res) => {
	// 获取未删除的项目总数
	const sql = 'select count(*) from project where project_delete=0';
	db.query(sql, (err, results) => {
		if (err) return res.cc(err);
		const listNumber = results[0]['count(*)'];
		if (listNumber === 0) return res.cc('当前没有数据');
		// 分页查询
		const page_num = req.query.page_num;
		const page_size = req.query.page_size;
		const params = [
			(parseInt(page_num) - 1) * parseInt(page_size),
			parseInt(page_size)
		]
		const sql = 'select * from project where project_delete=0 order by project_id desc limit ?,?';
		db.query(sql, params, (err, results) => {
			if (err) return res.cc(err);
			let arr = results.map((item) => {
				return Object.assign({}, {
					project_id: item.project_id
				}, {
					project_name: item.project_name
				}, {
					project_type: item.project_type
				}, {
					project_start_date: item.project_start_date
				}, {
					project_days: item.project_days
				}, {
					project_people_number: item.project_people_number
				}, {
					project_state: item.project_state
				}, {
					project_creator_id: item.project_creator_id
				}, {
					project_creator_date: item.project_creator_date
				})
			})
			// 将创建人id替换为创建人名字
			const sql = 'select * from user';
			db.query(sql, (err, results) => {
				if (err) return res.cc(err);
				for (let i = 0; i < arr.length; i++) {
					for (let j = 0; j < results.length; j++) {
						if (arr[i].project_creator_id == results[j].id) {
							arr[i].project_creator_name = results[j].nick_name
						}
					}
				}
				res.send({
					status: 0,
					message: '查询成功',
					data: arr,
					listNumber
				})
			})
		})
	})
}

// 批量删除项目
exports.deleteProjectList = (req, res) => {
	// 处理前端传过来的ids
	let arr = req.body.project_ids.split('@');
	let ids = '';
	for (var i = 0; i < arr.length; i++) {
		ids += "'" + arr[i] + "'" + ","
	}
	ids = ids.substr(0, ids.length - 1)
	const sql = "update project set project_delete=1 where project_id in(" + ids + ")";
	db.query(sql, (err, results) => {
		if (err) return res.cc(err)
		res.cc('删除成功', 0)
	})
}

// 获取已经上传的切片
exports.projectUploadAlready = async (req, res) => {
	let { HASH } = req.query;
	let path = `${uploadDir}/${HASH}`,
		fileList = [];
	try {
		fileList = fs.readdirSync(path);
		fileList = fileList.sort((a, b) => {
			let reg = /_(\d+)/;
			return reg.exec(a)[1] - reg.exec(b)[1];
		});
		res.send({
			status: 0,
			message: '',
			fileList: fileList
		});
	} catch (err) {
		res.send({
			status: 0,
			message: '',
			fileList: fileList
		});
	}
}

// 上传切片
exports.projectUploadChunk = async (req, res) => {
	try {
		let {
			fields,
			files
		} = await multipartyTool.multiparty_upload(req);
		let file = (files.file && files.file[0]) || {},
			filename = (fields.filename && fields.filename[0]) || "",
			path = '',
			isExists = false;
		// 创建存放切片的临时目录
		let [, HASH] = /^([^_]+)_(\d+)/.exec(filename);
		path = `${uploadDir}/${HASH}`;
		!fs.existsSync(path) ? fs.mkdirSync(path) : null;
		// 把切片存储到临时目录中
		path = `${uploadDir}/${HASH}/${filename}`;
		isExists = await multipartyTool.exists(path);
		if (isExists) {
			res.send({
				status: 0,
				message: 'file is exists',
				originalFilename: filename,
				servicePath: path.replace(__dirname, `${config.HOST}:${config.PORT}`)
			});
			return;
		}
		multipartyTool.writeFile(res, path, file, filename, true);
	} catch (err) {
		res.send({
			status: 1,
			message: err
		});
	}
}

// 合并切片
exports.projectUploadMerge = async (req, res) => {
	let { HASH, count } = req.body;
	try {
		let { filename, path } = await multipartyTool.merge(HASH, count);
		const sql = `UPDATE project SET source_file=? WHERE project_id=${req.body.project_id}`
		db.query(sql, path, (results, err) => {
			res.send({
				status: 0,
				message: '上传成功',
				originalFilename: filename,
				servicePath: `${config.HOST}:${config.PORT}${path}`
			})
		})
	} catch (err) {
		if(err){
			res.send({
				status: 1,
				message: err
			});
		}
	}
}

// 图片上传
exports.projectUploadSingle = (req, res) => {
	// 预上传
	// axios.post(`http://pan.baidu.com/rest/2.0/xpan/file?method=precreate&access_token=${config.access_token}`,{
		
	// }).then(response => {
	// 	console.log(response.data)
	// 	res.send({
	// 		status: 'success',
	// 		message: '上传成功',
	// 		response: {
	// 			url: config.HOST + ':' + config.PORT + '/img/123456.png'
	// 		}
	// 	})
	// }).catch(err => {
	// 	res.cc(err)
	// })
	
	
	fs.readFile(req.file.path, (err, data)=>{
		if (err) return res.cc('上传失败,请确认是否按照要求上传');
		// 头像命名
		let time = Date.now() + parseInt(Math.random() * 999) + parseInt(Math.random()*2222);
		let extname = req.file.mimetype.split('/')[1]
		let keepname = time + '.' + extname
		let fileAddressStr = '/img/' + keepname
		// 头像图像
		fs.renameSync(req.file.path, path.join(__dirname, '../static/img/' + keepname));
		// 将路径存入数据库
		const sql = 'insert into project_images(project_image, project_id) values (?,?)';
		db.query(sql, [fileAddressStr, req.body.project_id], (err, results) => {
			if (err) return res.send({
				status: 'fail',
				error: '上传失败，请检查网络或稍后重试'
			})
			res.send({
				status: 'success',
				message: '上传成功',
				response: {
					url: config.HOST + ':' + config.PORT + fileAddressStr
				}
			})
		})
	})
}

// 批量删除相册
exports.deleteProjectImage = (req, res) => {
	let idsStr = req.body.project_images_ids.replace(/@/g,',')
	// 多id查询 select * from b1 where id in (1,2,3,22);
	const sql = 'select * from project_images where project_images_id in (' + idsStr + ')';
	db.query(sql, (err, results) => {
		if (err) return res.cc(err);
		// 删除文件
		const uploadDir = path.resolve(__dirname, '../', 'static');
		for (let i = 0 ; i < results.length ; i++){
			try {
				fs.unlinkSync(`${uploadDir}${results[i].project_image}`)
			} catch(err) {
				return res.cc(err);
			}
		}
		// 删除数据库 delete from b1 where id in (1,2,3,22)
		const sql = 'delete from project_images where project_images_id in (' + idsStr + ')';
		db.query(sql, (err, results) => {
			if (err) return res.cc(err);
			res.cc('删除成功', 0)
		})
	})
}

// 初稿提交
exports.projectFirstDraft = (req, res) => {
	const sql = 'update project set project_state=1 where project_id=?';
	db.query(sql, req.body.project_id, (err, results) => {
		if (err) return res.cc(err);
		res.cc('操作成功', 0)
	})
}

// 改稿延长
exports.projectRewrite = (req, res) => {
	const sql = 'select * from project where project_id=?';
	db.query(sql, req.body.project_id, (err, results) => {
		if (err) return res.cc(err);
		// 查询项目当前修改次数，然后+1
		let amendment_no = results[0].amendment_no + 1
		// 将项目时间，修改次数更新到数据库中
		// UPDATE `bdm_oa`.`project` SET `project_end_date` = '2022-08-15', `amendment_no` = '1' WHERE (`project_id` = '3');
		const sql = 'update project set project_end_date=?, amendment_no=? where project_id=?';
		db.query(sql, [req.body.project_rewrite_date, amendment_no, req.body.project_id], (err, results) => {
			if (err) return res.cc(err);
			res.cc('操作成功', 0);
		})
	})
}

// 项目完结
exports.projectEnd = (req, res) => {
	const sql = 'update project set project_state=2 where project_id=?';
	db.query(sql, req.body.project_id, (err, results) => {
		if (err) return res.cc(err);
		res.cc('操作成功', 0)
	})
}

// 项目流单
exports.projectFail = (req, res) => {
	const sql = 'update project set project_state=3 where project_id=?';
	db.query(sql, req.body.project_id, (err, results) => {
		if (err) return res.cc(err);
		res.cc('操作成功', 0);
	})
}

// 删除项目文件
exports.deleteProjectFile = (req, res) => {
	const sql = 'select * from project where project_id=?'
	db.query(sql, req.body.project_id, (err,results) => {
		if(err) return res.cc(err)
		const uploadDir = path.resolve(__dirname, '../', 'static');
		fs.unlinkSync(`${uploadDir}${results[0].source_file}`)
		const sql = `UPDATE project SET source_file='' WHERE project_id=?`
		db.query(sql, req.body.project_id, (err, results) => {
			if(err) return res.cc(err)
			res.cc('删除成功', 0)
		})
	})
}

// 状态进度查询项目列表
exports.stateProjectList = (req, res) => {
	let sql = ''
	// 获取未删除的项目总数
	if(req.query.project_name){
		sql = `select count(*) from project where project_delete=0 and project_state=? and project_name like '%${req.query.project_name}%'`
		if(req.query.project_state == 5){
			sql = `select count(*) from project where project_delete=0 and project_name like '%${req.query.project_name}%'`
		}
	} else{
		sql = 'select count(*) from project where project_delete=0 and project_state=?'
	}
	db.query(sql, req.query.project_state, (err, results) => {
		if (err) return res.cc(err);
		const listNumber = results[0]['count(*)'];
		// 分页查询
		const page_num = req.query.page_num;
		const page_size = req.query.page_size;
		let params = [
				req.query.project_state,
				(parseInt(page_num) - 1) * parseInt(page_size),
				parseInt(page_size)
			]
		let sql = ''
		if(req.query.project_name){
			sql = `select * from project where project_state=? and project_delete=0 and project_name like '%${req.query.project_name}%' order by project_id desc limit ?,?`
			if(req.query.project_state == 5){
				sql = `select * from project where project_delete=0 and project_name like '%${req.query.project_name}%' order by project_id desc limit ?,?`
				params = [
						(parseInt(page_num) - 1) * parseInt(page_size),
						parseInt(page_size)
					]
			}
		} else {
			sql = 'select * from project where project_state=? and project_delete=0 order by project_id desc limit ?,?'
		}
		db.query(sql, params, (err, results) => {
			if (err) return res.cc(err);
			let arr = results.map((item) => {
				return Object.assign({}, {
					project_id: item.project_id
				}, {
					project_name: item.project_name
				}, {
					project_type: item.project_type
				}, {
					project_start_date: item.project_start_date
				}, {
					project_days: item.project_days
				}, {
					project_people_number: item.project_people_number
				}, {
					project_state: item.project_state
				}, {
					project_creator_id: item.project_creator_id
				}, {
					project_creator_date: item.project_creator_date
				})
			})
			// 将创建人id替换为创建人名字
			const sql = 'select * from user';
			db.query(sql, (err, results) => {
				if (err) return res.cc(err);
				for (let i = 0; i < arr.length; i++) {
					for (let j = 0; j < results.length; j++) {
						if (arr[i].project_creator_id == results[j].id) {
							arr[i].project_creator_name = results[j].nick_name
						}
					}
				}
				res.send({
					status: 0,
					message: '查询成功',
					data: arr,
					listNumber
				})
			})
		})
	})
}